package com.baseproject.datasource.get.procedure;

import android.support.annotation.Nullable;

import com.baseproject.datasource.Repository;
import com.baseproject.util.LogUtils;

import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by hp on 2017/8/17.
 */

public class CommonDataProcedure extends DataProcedure {

    public CommonDataProcedure(Class className) {
        super(className);
    }

    @Override
    public <T> Observable<List<T>> getList(Class<T> className) {
        List cached = getFromCache(Repository.getInstance().getCacheList());
        if (null != cached && cached.size() > 0) {
            LogUtils.d("cache data used! ");
            return Observable.from(cached).toList();
        }
        return localThenRemote(className);
    }

    public <T> Observable<List<T>> localThenRemote(Class<T> className)  {
        return Repository.getInstance().getListFromLocalDataSource(this, this.getClassName())
                .flatMap(new Func1<List, Observable<List>>() {// flatMap处理嵌套RxJava请求
                    @Override
                    public Observable<List> call(List contentList) {
                        if (null != contentList && contentList.size() > 0) {
                            return Observable.just(contentList);
                        } else {
                            return Repository.getInstance().getListFromRemoteDataSource(CommonDataProcedure.this,
                                    CommonDataProcedure.this.getClassName());
                        }
                    }
                });
    }

    @Nullable
    private  List getFromCache(Map<String, List> cacheList) {
        return cacheList.get(mLocalRequestParams.getUniqueKey());
    }

}
